

function GetLocationList(data)
{
    // data is in this format:  1,'TD1':2,'TD2'
    // so need to create chart xaxis from it by spliting it in two dimentional array
    var xaxisList = new Array(0);
    var temp;
    var index = 0;

    // JQuery Foreach loop
    $.each(data.split(":"), function() {
        temp = this.split(",");
        xaxisList[index++] = new Array(temp[0],temp[1]);
    });
    return xaxisList;
}

function LocationToVerify(fishDetailList, fishName, locationID, startIndex)
{
    var _FLAG = false;
    var temp = "";

    // FishDetail Format: [LocID],[Fishname],[Quantity],[FishID]
    if(startIndex < (fishDetailList.length - 1)){
        for(var findex = (startIndex + 1); findex < fishDetailList.length; findex++){
            // If Next Location ID same then proceed otherwise skip as location ids are sorted so if different this means now this ID will not occur
            temp = fishDetailList[findex].split(",");
            if(temp[0] == locationID){
                if(temp[1] == fishName){
                    _FLAG = true;
                    break;
                }
            }
            else
                break;
        }
    }

    return _FLAG;
}

function DrawChart(params,year_value)
{
var ul="";
    if (year_value==undefined)
        {
            ul="http://" + location.hostname + "/main/Chart_Data?search=" + params;
        }
    else
        {
             ul="http://" + location.hostname + "/main/Chart_Data?search=" + params+"DATE_FLAG"+year_value;
        }
    downloadUrl(url = ul, function(returnVal) {
    var plotarea = null;
       if(returnVal != "")
       {

            var rawData = returnVal.split("|");

            if(rawData.length == 5)
            {

                var xaxisList = GetLocationList(rawData[0]);

                // data is in this format:  1,'Fish1',1.00:2,'Fish2',2.00
                // so need to create chart xaxis from it by spliting it in two dimentional array
                var dataList = new Array(0);
                var temp;
                var temp2;
                var fishName = "";
                var fishID = "";
                var arrIndex = 0;
                var arrIndex2 = 0;
                var arrIndex3 = 0;
                var arrIndex4 = 0;
                var tempDataArray = new Array(0);
                var tempDataArray2 = new Array(0);
                var tempDataArray3 = new Array(0);

                var fishDetailList = rawData[1].split(":");

                for(var fishIndex = 0; fishIndex < fishDetailList.length; fishIndex++){

                    temp = fishDetailList[fishIndex].split(",");

                    if((temp[1] !=  fishName || fishName == "") && !containsObj(tempDataArray2, temp[3]))
                    {
                        fishName = temp[1];

                        for(var fishIndex2 = 0; fishIndex2 < fishDetailList.length; fishIndex2++){
                            temp2 = fishDetailList[fishIndex2].split(",");

                            if(temp2[1] == fishName){
                                tempDataArray[arrIndex++] = new Array(temp2[0], parseInt( temp2[2]));
                                tempDataArray3[arrIndex4++] =temp2[0];

                            }
                            else
                            {
                                if(!containsObj(tempDataArray3, temp2[0]) && !LocationToVerify(fishDetailList, fishName, temp2[0], fishIndex2)){
                                        tempDataArray[arrIndex++] = new Array(temp2[0], 0);
                                        tempDataArray3[arrIndex4++] = temp2[0];

                                }
                            }
                        }

                        //alert(fishName + "--> " + tempDataArray);
                        dataList[arrIndex3++] = {label: fishName, data: tempDataArray.sort()};
                        tempDataArray2[arrIndex2++] = temp[3];// fishName ;

                        tempDataArray = new Array(0);    // Clearing array for next data
                        tempDataArray3 = new Array(0);    // Clearing array for next data
                        arrIndex = 0;               // Clearing array index for next data
                        arrIndex4 = 0;
                    }
                }

                // Clear Chart Legend
                //document.getElementById("spUnitList").innerHTML = "";
                //document.getElementById("spYearList").innerHTML = "";
                //document.getElementById("spDepthList").innerHTML = "";

                // Add nodes in Chart Legend (unit)
                //document.getElementById("spUnitList").appendChild(document.createTextNode(rawData[2]));

                // Add nodes in Chart Legend (unit)
                //document.getElementById("spDepthList").appendChild(document.createTextNode(rawData[4]));

//                var yearList = rawData[3].split(",");
//
//                for(var idx = 0; idx < yearList.length; idx++)
//                {
//                    var link = document.createElement ('A');
//                    link.appendChild (document.createTextNode (yearList[idx]));
//                    link.setAttribute ('href', '#');
//                    link.setAttribute ('onclick', "refreshChart('"+ yearList[idx] +"');");
//
//                    // Add nodes in Chart Legend (Year)
//                    document.getElementById("spYearList").appendChild(link);
//                }

                var options = {
                             series: {
                                 stack: true,
                                 lines: {
                                     show: false,
                                     steps: false
                                 },
                                 bars: {
                                     show: true,
                                     lineWidth: 2, // in pixels
                                     barWidth: 0.6,
                                     align: 'center',
//                                     fill: true,
//                                     fillColor: null,
                                     horizontal: false // when horizontal, left is now top
                                 },
                                 shadowSize: 3
                             },
                             grid: {
                backgroundColor: {colors: ["#fff", "#eee"]},
                canvasText: {show: true, font: "sans 8px"},
                labelMargin: 10
                                },

                             legend: {
                                 show: true,
                                 noColumns: 3,
//                                 labelFormatter: null, // fn: string -> string
//                               labelWidth: 30,
//                                 labelBoxBorderColor: "#ccc", // border color for the little label boxes
                                 position: "ne",
                                 container:document.getElementById("spFishList"),
                                 backgroundColor: null, // null means auto-detect
                                 backgroundOpacity: 0.85 // set to 0 to avoid background
                             },
                             selection: {mode: "x"},
//                             color: "rgb(30, 180, 20)",
                           xaxis: {ticks: xaxisList, autoscaleMargin: null},
                           yaxis: {labelWidth:25}

                    };


                //document.getElementById("reportarea").style.width = 100 + "%";
                plotarea = $("#chart_canvas");

                $.plot( plotarea , dataList,options);

                // Hide No Data Available Message

                //document.getElementById("hide_data").style.display = "none";
                document.getElementById("spFishList").style.display = "block";
            }
        }
        else
        {
            var options_blank = {
                         series: {
                             stack: 0,
                             lines: {
                                 show: false,
                                 steps: false
                             },
                             bars: {
                                 show: true,
                                 lineWidth: 2, // in pixels
                                 barWidth: 0.6,
                                 align: 'left',
                                 fill: true,
                                 fillColor: null,
                                 horizontal: false // when horizontal, left is now top
                             },
                             shadowSize: 3
                         },
                         legend: {
                             show: true,
                             noColumns: 10000,
                             labelFormatter: null, // fn: string -> string
                             labelWidth: 30,
                             labelBoxBorderColor: "#ccc", // border color for the little label boxes
                             position: "ne",
                             margin: 5,
                             container: null,
                             backgroundColor: null, // null means auto-detect
                             backgroundOpacity: 0.85 // set to 0 to avoid background
                         },
                         selection: {mode: "x"},
                         color: "rgb(30, 180, 20)",
                         xaxis: {ticks: 0, autoscaleMargin: null},
                         grid: {hoverable: true, autoHighlight: true, aboveData: true},
                         zoom: {interactive: true},
                         pan: {interactive: true},
                         yaxis: {min: 0, tickDecimals: 0, overflow: scroll}
                };

                plotarea = $("#chart_canvas");
                $.plot( plotarea , new Array(0,0), options_blank );

                
                document.getElementById("chart_canvas").innerHTML = "No Data Found";
//                alert('a');
                document.getElementById("spFishList").style.display = "none";


        }
    });
}

// Returns TRUE if Array contains the object otherwise returns FALSE
function containsObj(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}

function handleResize() {
  return windowHeight() - document.getElementById('header').offsetHeight;
}

function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight)
    return self.innerHeight;
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  // IE 5
  if (document.body)
    return document.body.clientHeight;
  // Just in case.
  return 0;
}

$(document).ready(function(){
    $(".report-slide").click(function(){

            $("#reportarea").slideToggle("slow");
            $(this).toggleClass("active");

            if(document.getElementById("hfBtnChartStatus").value == "0")
            {
                document.getElementById("hfBtnChartStatus").value = 1;
            }
            else if(document.getElementById("hfBtnChartStatus").value == "1")
            {
                document.getElementById("hfBtnChartStatus").value = 0;
            }
            if (Flag_Search_Panel_Status=="Search")
                {setFilter("2", "");}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2", "");}

return false;
    });
});

//$(function() {
//        $( "#reportarea" ).accordion({
//        });
//});


function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing(){}

function parseXml(str)
{
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}

// Set the Chart width to 100% when RightNav Collapsed
function EnlargeChart(dvChart, dvRightNavStatus)
{

    if( dvChart) {
        if( dvRightNavStatus == "0")
        {
            dvChart.style.width = 100 + "%";

        }
        else
            {
            dvChart.style.width = 60 + "%";
            }

        if(dvChart.style.display != ""){

        }

        if (Flag_Search_Panel_Status=="Search")
                {setFilter("2", "");}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2", "");}

    }
}
function refreshChart(year_para)
{
    if (Flag_Search_Panel_Status=="Search")
                {setFilter("2","", year_para);}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2","", year_para);}

}
function SaveSearchData()
{

    var para="";
    if (Flag_Search_Panel_Status=="Search")
                {
                   para= setFilter("2","", "",true);
              }
            else if (Flag_Search_Panel_Status=="History")
                {para=setFilter_History("2","","",true);
                }
                if (para!="")
                    {
                        var tmp=para.split("OLY",para.length);

                        window.open("http://" + location.hostname +"/searchresult/ZipData/search/"+tmp[0]+"OLY"+tmp[1]);

                        }
                else
                    {
                        alert("Please select data first");
                    }

}

function saveFlotGraphAsPNG(placeholderID, targetID) {

//          var divobj = document.getElementById(placeholderID);
//
//          var oImg = Canvas2Image.saveAsPNG(divobj.childNodes[0], true);
//
//          if (!oImg) {
//              alert("Sorry, this browser is not capable of saving PNG files!");
//              return false;
//          }
//
//          oImg.id = "canvasimage";
//
//            saveImageAs(oImg);
//
///          document.getElementById(targetID).removeChild(document.getElementById(targetID).childNodes[0]);
///          document.getElementById(targetID).appendChild(oImg);


        }

function LoadUserConnectionList() {
    $.post("http://"+location.hostname+"/home/ConnectionAutocomplete", {}, function(data) {
        $( "#txtMailTo" ).autocomplete(data.split("###"),{
            minChars: 0,
            max: 10,
            autoFill: true,
            mustMatch: false,
            matchContains: "word",
            scrollHeight: 220
        }
        );
    });
}


function findValue(li) {
    if( li == null ) return alert("No match!");

    // if coming from an AJAX call, let's use the CityId as the value
    if( !!li.extra ) var sValue = li.extra[0];

    // otherwise, let's just display the value in the text box
    else var sValue = li.selectValue;

    //alert("The value you selected was: " + sValue);
}

function selectItem() {
    alert('li');
    return;
}

function formatItem(row) {
    return row[0] + " (id: " + row[0] + ")";
}

function lookupAjax(){
    var oSuggest = $("#txtMailTo")[0].autocompleter;

    oSuggest.findValue();

    return false;
}

function lookupLocal(){
    var oSuggest = $("#txtMailTo")[0].autocompleter;
    oSuggest.findValue();

    return false;
}

// Use to Print Default Text
$(document).ready(function() {
    $.defaultText();
});

function ShowPopUp(dialogID) {

	//select all the a tag with name equal to modal
	
		//Cancel the link behavior
		//e.preventDefault();

		//Get the A tag
		var id = dialogID;

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(100);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);

		//transition effect
		$(id).fadeIn(300);

	

	

}
$(document).ready(function(){
//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior

		e.preventDefault();

		$('#mask').hide();
		$('.window').hide();

                // Total Message Count Should be updated on Dialog Close
                
	});

	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});
});

function showattributereport(locationarray)
{


var lArray=locationarray.split(",");

$("#newOption").html("<label style='font-size:8pt; font-weight: bold; color: #f6a828'>Select Location: </label><select style='font-size:8pt; font-weight:bold; color:#1c94c4; width: 250px' id='locationselection' onchange=LoadAttributes(this.value)></select>");
$("#newOptionAttribute").html("<label style='font-size:8pt; font-weight: bold; color: #f6a828'>Select Attribute: </label><select style='width: 250px; font-size:8pt; font-weight:bold; color:#1c94c4' id='attributeselection' onchange=LoadAttributeReport()></select>");
for (a=0;a<lArray.length;a++)
    {

            $("#locationselection").append("<option >"+ lArray[a] +"</option>");

    }
                                $("#locationselection").val(lArray[0]);


LoadAttributes(lArray[0]);


                                var id = "#locationattributereport";

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(100);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		//Set the popup window to center
		$(id).css('width', winW-490);
                $(id).css('height', winH-150);
                $("#AttributeReport_canvas").css('height',$(id).height()-80);
                $("#AttributeReport_canvas").css('width', $(id).width()-20);
                $(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);


		//transition effect
		$(id).fadeIn(200);






}

function LoadAttributes(locationref)
{

  
  $("#attributeselection").html('<img src="/images/loading/loading9.gif">');
    $.post("http://"+location.hostname+"/general/LoadAttribute", {search: locationref}, function(data) {

                                
                                $("#attributeselection").html("");
                                $("#attributeselection").append(data);
                                LoadAttributeReport();
				});



}
function LoadAttributeReport()
{
var chk=document.getElementById("attributeselection");
var locationarray= chk.value;

                var ul="";

$("#AttributeReport_canvas").html('<img src="/images/loading/loading9.gif">');


//var locationarray="2FLG_ATTRIBUTE_REPORTTD1";
ul="http://" + location.hostname + "/general/LoadAttributeReport?search=" + locationarray;

downloadUrl(url = ul, function(returnVal) {
    var plotarea = null;
       if(returnVal != "")
       {

            var rawData = returnVal.split("|");

            if(rawData.length == 2)
            {

                var xaxisList = GetLocationList(rawData[0]);

                // data is in this format:  1,'Fish1',1.00:2,'Fish2',2.00
                // so need to create chart xaxis from it by spliting it in two dimentional array
                var dataList = new Array(0);
                var temp;
                var temp2;
                var fishName = "";
                var fishID = "";
                var arrIndex = 0;
                var arrIndex2 = 0;
                var arrIndex3 = 0;
                var arrIndex4 = 0;
                var tempDataArray = new Array(0);
                var tempDataArray2 = new Array(0);
                var tempDataArray3 = new Array(0);

                var fishDetailList = rawData[1].split(":");

                for(var fishIndex = 0; fishIndex < fishDetailList.length; fishIndex++){

                    temp = fishDetailList[fishIndex].split(",");

                    if((temp[1] !=  fishName || fishName == "") && !containsObj(tempDataArray2, temp[3]))
                    {
                        fishName = temp[1];

                        for(var fishIndex2 = 0; fishIndex2 < fishDetailList.length; fishIndex2++){
                            temp2 = fishDetailList[fishIndex2].split(",");

                            if(temp2[1] == fishName){
                                tempDataArray[arrIndex++] = new Array(temp2[0], parseInt( temp2[2]));
                                tempDataArray3[arrIndex4++] =temp2[0];

                            }
                            else
                            {
                                if(!containsObj(tempDataArray3, temp2[0]) && !LocationToVerify(fishDetailList, fishName, temp2[0], fishIndex2)){
                                        tempDataArray[arrIndex++] = new Array(temp2[0], 0);
                                        tempDataArray3[arrIndex4++] = temp2[0];

                                }
                            }
                        }

                        //alert(fishName + "--> " + tempDataArray);
                        dataList[arrIndex3++] = {label: fishName, data: tempDataArray.sort()};
                        tempDataArray2[arrIndex2++] = temp[3];// fishName ;

                        tempDataArray = new Array(0);    // Clearing array for next data
                        tempDataArray3 = new Array(0);    // Clearing array for next data
                        arrIndex = 0;               // Clearing array index for next data
                        arrIndex4 = 0;
                    }
                }
                var options = {
                             series: {
                                 stack: true,
                                 lines: {
                                     show: false,
                                     steps: false
                                 },
                                 bars: {
                                     show: true,
                                     lineWidth: 2, // in pixels
                                     barWidth: 0.6,
                                     align: 'center',
//                                     fill: true,
//                                     fillColor: null,
                                     horizontal: false // when horizontal, left is now top
                                 },
                                 shadowSize: 3
                             },
                             grid: {
                backgroundColor: {colors: ["#fff", "#eee"]},
                canvasText: {show: true, font: "sans 8px"},
                labelMargin: 10
                                },

                             legend: {
                                 show: true,
                                 noColumns: 3,
//                                 labelFormatter: null, // fn: string -> string
//                               labelWidth: 30,
//                                 labelBoxBorderColor: "#ccc", // border color for the little label boxes
                                 position: "ne",
//                                 container:document.getElementById("spFishList"),
                                 backgroundColor: null, // null means auto-detect
                                 backgroundOpacity: 0.85 // set to 0 to avoid background
                             },
                             selection: {mode: "x"},
//                             color: "rgb(30, 180, 20)",
                           xaxis: {ticks: xaxisList, autoscaleMargin: null},
                           yaxis: {labelWidth:25}
                    };


                //document.getElementById("reportarea").style.width = 100 + "%";
                plotarea = $("#AttributeReport_canvas");

                $.plot( plotarea , dataList,options);


            }
        }

    });



}




function ShowMessage(link, id)
{
    var msgID = 0;
    var url = "http://" + location.hostname + "/home/showMessage?id=" + id;
     downloadUrl(url, function(returnVal){
         var returnedData = returnVal.split("###");
         msgID = returnedData[0];
         var msgID = document.getElementById("hfMsgID");
         if(msgID)
         {
            msgID.value = returnedData[0];
         }

         var msgSender = document.getElementById("txtMessageSender");
         if(msgSender)
         {
            msgSender.innerHTML = returnedData[1];
         }

         var msgSubjH3 = document.getElementById("txtMessageSubjectH3");
         if(msgSubjH3)
         {
            msgSubjH3.innerHTML = "Subject: " + returnedData[2].replace("***","###");
         }

         var msgBodyH3 = document.getElementById("dvMessageBody");
         if(msgBodyH3)
         {
            msgBodyH3.innerHTML = returnedData[3].replace("***", "###");
         }

         url = "http://" + location.hostname + "/home/getMessageReply?mid=" + msgID.value;
         
         downloadUrl(url, function(returnVal){            
            $("#dvMessageReply").html(returnVal);
         });
     });
     
     ShowPopUp("#readmessage_");
}

function deleteMessage(ctrlDelete, messageID)
{
    if(ctrlDelete.checked)
    {
        if(confirm("Are you sure you want to delete?"))
        {
            url = "http://" + location.hostname + "/home/deleteMessage?id=" + messageID;
            downloadUrl(url, function(returnVal){

                if(returnVal == "1")
                {
                    location.reload();
                }
            });
        }
        else
        {
            ctrlDelete.checked = false;
        }
    }
}

function getMessageID()
{
    var msgID = document.getElementById("hfMsgID");
    return msgID.value;
}

function sendMessageReplay(msgID, replyBody, uid)
{

    alert(uid);
}
